package com.hospital.diagnosis.module.controller;

import com.hospital.common.base.PageResult;
import com.hospital.common.base.Result;
import com.hospital.common.base.ThreadAttributes;
import com.hospital.common.dto.diagnosis.module.DiagnosisApplicationDTO;
import com.hospital.common.dto.diagnosis.module.DiagnosisRecordDTO;
import com.hospital.common.pojo.TDiagnosisRecord;
import com.hospital.common.utils.ThreadLocalUtils;
import com.hospital.common.vo.data.simulation.InspectionReportVo;
import com.hospital.diagnosis.module.exception.ServiceException;
import com.hospital.diagnosis.module.service.DiagnosisRecordService;
import com.hospital.diagnosis.module.vo.DiagnosisRecordTitleVo;
import com.hospital.diagnosis.module.vo.DiagnosisVo;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.hospital.diagnosis.module.exception.enums.ExceptionCode.FORBIDDEN;
import static com.hospital.diagnosis.module.exception.enums.ExceptionCode.RECORD_NOT_FOUND;

/**
 * 诊疗记录相关接口
 */
@RestController
@RequestMapping("/DiagnosisRecord")
public class DiagnosisRecordController
{
    @Autowired
    private DiagnosisRecordService diagnosisRecordService;


    /**
     * 基于医生、患者姓名分页获取诊疗记录标题列表
     * @param patientName 患者姓名 |张三
     * @param doctorName 医生姓名 |李四
     * @param startTime 开始时间 |2023-01-01
     * @param endTime 结束时间 |2023-01-01
     * @param pageNum   当前页 |1
     * @param pageSize  页大小 |10
     * @return 诊疗记录标题列表（分页）
     */
    @GetMapping("/getDiagnosisRecordListByName")
    public Result getDiagnosisRecordListByName(@RequestParam(value = "patientName",required = false) String patientName,
                                               @RequestParam(value = "doctorName",required = false) String doctorName,
                                               @RequestParam(value = "startTime",required = false) String startTime,
                                               @RequestParam(value = "endTime",required = false) String endTime,
                                               @RequestParam(value = "pageNum") @NotNull(message = "pageNum不能为空") Integer pageNum,
                                               @RequestParam(value = "pageSize") @NotNull(message = "pageSize不能为空") Integer pageSize)
    {
        ThreadAttributes ta =ThreadLocalUtils.get();
        Long patientId=ta.getRoleType()==0?ta.getUserId():null;
        Long doctorId=ta.getRoleType()==1?ta.getUserId():null;


        Integer count=diagnosisRecordService.getDiagnosisRecordCountByName(patientId,doctorId,patientName,doctorName,startTime,endTime);

        if(count==0)
        {
            return Result.success("未找到诊疗记录", null);
        }

        List<DiagnosisRecordTitleVo> drtList = diagnosisRecordService.getDiagnosisRecordListByName(patientId,doctorId,patientName, doctorName, startTime, endTime, pageNum, pageSize);

        return Result.success("列表获取成功", new PageResult((long)count,drtList));
    }

    /**
     * 基于医生ID获取诊疗记录数量
     * @return 诊疗记录数量
     */
    @GetMapping("/getDiagnosisRecordCountByDoctorId")
    public Result getDiagnosisRecordCountByDoctorId()
    {
        ThreadAttributes ta =ThreadLocalUtils.get();
        Long doctorId=ta.getRoleType()==1?ta.getUserId():0L;

        Integer count=diagnosisRecordService.getDiagnosisRecordCountByDoctorId(doctorId);
        return Result.success("获取成功", count);
    }

    /**
     * 基于患者ID分页获取诊疗记录标题列表
     * @param patientId 患者ID |1
     * @param pageNum   当前页 |1
     * @param pageSize  页大小 |10
     * @return 诊疗记录标题列表（分页）
     */
    @GetMapping("/getDiagnosisRecordListByPatientId")
    public Result getDiwagnosisRecordListByPatientId(@RequestParam("patientId") @NotNull(message = "patientId不能为空") Long patientId,
                                                    @RequestParam(value = "pageNum") @NotNull(message = "pageNum不能为空") Integer pageNum,
                                                    @RequestParam(value = "pageSize") @NotNull(message = "pageSize不能为空") Integer pageSize)
    {


        Integer count=diagnosisRecordService.getDiagnosisRecordCountByPatientId(patientId);

        if(count==0)
        {
            return Result.success("未找到诊疗记录", null);
        }

        List<DiagnosisRecordTitleVo> drtList = diagnosisRecordService.getDiagnosisRecordListByPatientId(patientId, pageNum, pageSize);

        return Result.success("列表获取成功", new PageResult((long)count,drtList));
    }

    /**
     * 基于医生ID分页获取诊疗记录标题列表
     * @param doctorId 医生ID |1
     * @param pageNum   当前页 |1
     * @param pageSize  页大小 |10
     * @return 诊疗记录标题列表（分页）
     */
    @GetMapping("/getDiagnosisRecordListByDoctorId")
    public Result getDiagnosisRecordListByDoctorId(@RequestParam("doctorId") @NotNull(message = "doctorId不能为空") Long doctorId,
                                                   @RequestParam(value = "pageNum") @NotNull(message = "pageNum不能为空") Integer pageNum,
                                                   @RequestParam(value = "pageSize") @NotNull(message = "pageSize不能为空") Integer pageSize)
    {
        Integer count=diagnosisRecordService.getDiagnosisRecordCountByDoctorId(doctorId);

        if(count==0)
        {
            return Result.success("未找到诊疗记录", null);
        }

        List<DiagnosisRecordTitleVo> drtList = diagnosisRecordService.getDiagnosisRecordListByDoctorId(doctorId, pageNum, pageSize);


        return Result.success("列表获取成功", new PageResult((long)count,drtList));
    }

    /**
     * 基于诊疗记录ID获取诊疗记录详情
     * @param Id 诊疗记录ID |1
     * @return 诊疗记录详情
     */
    @GetMapping("/getDiagnosisRecordById")
    public Result getDiagnosisRecordById(@RequestParam("Id") @NotNull(message = "Id不能为空") Long Id){
        TDiagnosisRecord diagnosisRecord = diagnosisRecordService.getDiagnosisRecordById(Id);
        if(ObjectUtils.isEmpty(diagnosisRecord)){
            throw new ServiceException(RECORD_NOT_FOUND);
        }
        return Result.success("诊疗记录获取成功", diagnosisRecord);
    }

    /**
     * 添加诊疗记录
     * @param diagnosisRecord
     * @return 添加结果
     */
    @PostMapping("/addDiagnosisRecord")
    public Result addDiagnosisRecord(@RequestBody @Validated DiagnosisRecordDTO diagnosisRecord){
        ThreadAttributes ta = ThreadLocalUtils.get();
        if(ta==null||ta.getRoleType()!=1){
            System.out.println(ta.toString());
            throw new ServiceException(FORBIDDEN);
        }
        diagnosisRecordService.addDiagnosisRecord(ta.getUserId(),diagnosisRecord);
        return Result.success("添加成功");
    }

    /**
     * 添加检验申请
     * @param diagnosis
     * @return 添加结果
     */
    @PostMapping("/addDiagnosisApplication")
    public Result addDiagnosisApplication(@RequestBody @Validated DiagnosisApplicationDTO diagnosis){
        ThreadAttributes ta = ThreadLocalUtils.get();
        if(ta==null||ta.getRoleType()!=1){
            throw new ServiceException(FORBIDDEN);
        }
        diagnosisRecordService.addDiagnosisApplication(ta.getUserId(),diagnosis);
        return Result.success("添加成功");
    }

    /**
     * （患者）分页获取检验申请列表
     * @param doctorName 医生姓名 |1
     * @param startTime 开始时间 |2025-09-21
     * @param endTime  结束时间 |2025-09-22
     * @param pageNum  当前页|1
     * @param pageSize 页大小|12
     * @return 检验申请记录列表（分页）
     */
    @GetMapping("/getDiagnosisApplication")
    public Result getDiagnosisApplication(@RequestParam(value = "doctorName",required = false) String doctorName,
                                          @RequestParam(value = "startTime",required = false) String startTime,
                                          @RequestParam(value = "endTime",required = false) String endTime,
                                          @RequestParam(value = "pageNum") @NotNull(message = "pageNum不能为空") Integer pageNum,
                                          @RequestParam(value = "pageSize") @NotNull(message = "pageSize不能为空") Integer pageSize){
        ThreadAttributes ta = ThreadLocalUtils.get();
        if(ta==null||ta.getRoleType()!=0){
            throw new ServiceException(FORBIDDEN);
        }

        if(ObjectUtils.isEmpty(doctorName)){
            doctorName = "";
        }
        if(ObjectUtils.isEmpty(startTime)){
            startTime = "";
            endTime = "";
        }

        Integer count=diagnosisRecordService.getDiagnosisApplicationCountByPatientId(ta.getUserId(),doctorName,startTime,endTime);
        if(count==0)
        {
            return Result.success("未找到检验申请", null);
        }
        List<DiagnosisVo> diagnosisList = diagnosisRecordService.getDiagnosisApplicationByPatientId(ta.getUserId(), doctorName,startTime,endTime,pageNum, pageSize);
        return Result.success("列表获取成功", new PageResult((long)count,diagnosisList));
    }

    /**
     * 基于患者ID获取检查结果列表
     * @param patientId 患者ID |1
     * @return 检查结果列表
     */
    @GetMapping("/getDiagnosisResultByPatientId")
    public Result getDiagnosisResultByPatientId(@RequestParam(value = "patientId",required = false) Long patientId){
        ThreadAttributes ta = ThreadLocalUtils.get();
        if(ta==null){
            throw new ServiceException(FORBIDDEN);
        }
        if(ta.getRoleType()==0){
            patientId = ta.getUserId();
        }

        List<InspectionReportVo> inspectionReportList=diagnosisRecordService.getDiagnosisResultByPatientId(patientId);
        return Result.success("列表获取成功", inspectionReportList);
    }


}
